

#import "NSAttributedString+Additon.h"

@implementation NSAttributedString (Additon)
/*创建一个图标在上,文字在下的按钮
 
 如何使用:
     // 创建属性文本
     NSAttributedString* str = [NSAttributedString imageTextWithImage:[UIImage imageNamed:imageName] imageWH:35 title:title fontSize:14 titleColor:[UIColor whiteColor] spacing:7];
     // 创建button
     UIButton* topViewButton = [[UIButton alloc] init];
     btn.titleLabel.numberOfLines = 0;//一定记得这一步,否则可能不成功
     btn.titleLabel.textAlignment = NSTextAlignmentCenter;
     [topViewButton setAttributedTitle:str forState:UIControlStateNormal];
 */
+ (instancetype)imageTextWithImage:(UIImage *)image imageWH:(CGFloat)imageWH title:(NSString *)title fontSize:(CGFloat)fontSize titleColor:(UIColor *)titleColor spacing:(CGFloat)spacing {
    // 文本字典
    NSDictionary *titleDict = @{NSFontAttributeName : [UIFont systemFontOfSize:fontSize],
                                NSForegroundColorAttributeName : titleColor};
    NSDictionary *spacingDict = @{NSFontAttributeName : [UIFont systemFontOfSize:spacing]};

    // 图片文本
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    attachment.bounds = CGRectMake(0, 0, imageWH, imageWH);
    NSAttributedString *imageText = [NSAttributedString attributedStringWithAttachment:attachment];

    // 换行文本
    NSAttributedString *lineText = [[NSAttributedString alloc] initWithString:@"\n\n" attributes:spacingDict];

    // 按钮文字
    NSAttributedString *text = [[NSAttributedString alloc] initWithString:title attributes:titleDict];

    // 合并文字
    NSMutableAttributedString *attM = [[NSMutableAttributedString alloc] initWithAttributedString:imageText];
    [attM appendAttributedString:lineText];
    [attM appendAttributedString:text];

    return attM.copy;
}

#pragma mark


@end
